#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;

// 函数对象的本质：重载结构体/类的()运算符

// 应用实例1：sort比较器
struct my_greater {
    bool operator()(int a, int b) const {
        return a > b;
    }
};

// 应用实例2：find_if
class my_find
{
    public:
    bool operator()(int n) {
        return n % 2 == 0;
    }
};

// 应用2：携带状态计数
class my_counter
{
    int count;

public:
    my_counter() : count(0) {}
    void operator()() {
        ++count;
        cout << "call " << count << " times"<< endl;
    }
};

// 应用3：字符串拼接器
class string_apender
{
    string m_sep;

public:
    string_apender(const string &sep) : m_sep(sep) {}
    string operator()(const string &a, const string &b) const
    {
        return a + m_sep + b;
    }
};

int main()
{
    //
    vector<int> vec = {1, 3, 5, 4, 6};

    //vector<int>::iterator idx = find_if(vec.begin(), vec.end(), my_find());
    auto idx = find_if(vec.begin(), vec.end(), my_find());
    cout << "数组有偶数为 " << (idx != vec.end()) << endl;

    for (int i = 0; i < vec.size(); i++) {
        cout << vec[i] << ",";
    }
    cout << endl; 

    sort(vec.begin(), vec.end());

    for (int i = 0; i < vec.size(); i++) {
        cout << vec[i] << ",";
    }
    cout << endl;

    sort(vec.begin(), vec.end(), my_greater());

    for (int i = 0; i < vec.size(); i++) {
        cout << vec[i] << ",";
    }
    cout << endl;

    //
    my_counter count1;
    count1();
    count1();

    //
    vector<string> strs = {"hello", "world", "from", "c++"};
    string res = accumulate(strs.begin(), strs.end(), string(), string_apender(" "));
    cout << res << endl;
}



// g++ -Wall -Wextra -O2 function_object.cpp -o build/function_object